import React, { Component } from 'react'
import { Alert, Card, Breadcrumb, Steps, Tabs, Form, Input, Cascader, message, Space, Tag, Upload, Button, Modal } from 'antd'
import { PlusOutlined, StrikethroughOutlined } from '@ant-design/icons'
import { addGood, getAttributesById, getCategories } from '../../../api/goods'
import QuillEditor from '../../../components/quillEditor'
const {Step} = Steps
const {TabPane}  = Tabs
export default class AddGood extends Component {
  state = {
    currentStep:0,
    addGoodForm:{
      goods_name: '',
      goods_cat : [],//      | 以为','分割的分类列表                             | 不能为空 |
      goods_price: undefined,//     | 价格                                              | 不能为空 |
      goods_number: undefined,//    | 数量                                              | 不能为空 |
      goods_weight: undefined, //    | 重量                                              | 不能为空 |
      goods_introduce: '', // | 介绍                                              | 可以为空 |
      pics: {},//            | 上传的图片临时路径（对象）                        | 可以为空 |
      attrs: [], //           | 商品的参数（数组），包含 `动态参数` 和 `静态属性` | 可以为空 |
    },
    categories:[],
    manyAttrList: [],
    onlyAttrList: [],
    previewImage: '',
    previewVisible: false,
    previewTitle: ''
  }
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };
  getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  handleCancel = () => this.setState({ previewVisible: false });
  setBasicalValues = (changedValues, allValues) => {
    const { addGoodForm } = this.state
    let newForm = {...addGoodForm,...allValues}
    this.setState({
      addGoodForm: newForm
    })
  }
  getCateList = async () => {
    const res = await getCategories();
    if(res.meta.status !== 200){
      return message.error(res.meta.msg)
    }
    this.setState({
      categories: res.data
    })
  }
  getAttrList = async (type) => {
    const res = await getAttributesById(this.state.addGoodForm.goods_cat[2],type)
    if(res.meta.status !== 200){
      return message.error(res.meta.msg)
    }
    if(type==='many'){
      await this.setState({
        manyAttrList: res.data
      })
      
    }else{
      this.setState({
        onlyAttrList: res.data
      })
    }
  }
  changeTab =async (value) => {
    if(this.state.currentStep===0 && this.state.addGoodForm.goods_cat.length!==3){
      message.warning("请先选择商品分类!")
      this.setState({
        currentStep: 0
      })
    }else{
      this.getAttrList('many')
      this.getAttrList('only')
      this.setState({
        currentStep: value * 1
      })
    }
  }
  getContent = value => {
    const { addGoodForm } = this.state;
    addGoodForm.goods_introduce = value;
    this.setState({
      addGoodForm
    })
  }
  addGood = async () => {
    const { addGoodForm } = this.state
    addGoodForm.goods_cat = addGoodForm.goods_cat.join(',')
    const res = await addGood(addGoodForm);
    if(res.meta.status !== 201){
      return message.error(res.meta.msg)
    }else{
      message.success(res.meta.msg)
      this.props.history.push('/admin/good-list')
    }
  }
  componentDidMount(){
    this.getCateList()
  }
  render() {
    return (
      <div>
        <Card>
          <Breadcrumb style={{marginBottom:'10px'}}>
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item>商品管理</Breadcrumb.Item>
            <Breadcrumb.Item>添加商品</Breadcrumb.Item>
          </Breadcrumb>
          <Alert style={{textAlign:'center',marginBottom:'10px'}} message="添加商品信息" type="info"  />
          <Steps style={{marginBottom:'10px'}} size="small" current={this.state.currentStep}>
            <Step title="基本信息" />
            <Step title="商品参数" />
            <Step title="商品属性" />
            <Step title="商品图片" />
            <Step title="商品描述" />
            <Step title="完成" />
          </Steps>
          <Form onValuesChange={this.setBasicalValues} labelAlign="right" labelCol={{span:4}}>
            <Tabs tabPosition="left" onTabClick={this.changeTab} activeKey={this.state.currentStep+""}>
              <TabPane tab="基本信息" key="0">
                <Form.Item label="商品名称" name="goods_name"  rules={[{required:true,message:"请填写商品名称"}]}>
                  <Input />
                </Form.Item>
                <Form.Item label="商品重量" name="goods_weight"  rules={[{required:true,message:"请填写商品为重量"}]}>
                  <Input type="number"/>
                </Form.Item>
                <Form.Item label="商品数量" name="goods_number"  rules={[{required:true,message:"请填写商品数量"}]}>
                  <Input type="number" />
                </Form.Item>
                <Form.Item label="商品价格" name="goods_price"  rules={[{required:true,message:"请填写商品价格"}]}>
                  <Input type="number" />
                </Form.Item>
                <Form.Item label="商品分类" name="goods_cat" rules={[{required:true,message:"请选择商品分类"}]}>
                  <Cascader options={this.state.categories} fieldNames={{label:'cat_name',value:'cat_id'}}/>
                </Form.Item>
              </TabPane>
              <TabPane tab="商品参数" key="1">
                {this.state.manyAttrList.map(manyItem => {
                  return <Form.Item key={manyItem.attr_id} label={manyItem.attr_name}>
                    <Space>
                      {manyItem.attr_vals.split(' ').map(attrItem => {
                        return <Tag color="blue" closable key={attrItem}>{attrItem}</Tag>
                      })}
                    </Space>
                  </Form.Item>
                })}
              </TabPane>
              <TabPane tab="商品属性" key="2">
              {this.state.onlyAttrList.map(manyItem => {
                  return <Form.Item key={manyItem.attr_id} label={manyItem.attr_name}>
                    <Space>
                      {manyItem.attr_vals.split(' ').map(attrItem => {
                        return <Tag color="blue" closable key={attrItem}>{attrItem}</Tag>
                      })}
                    </Space>
                  </Form.Item>
                })}
              </TabPane>
              <TabPane tab="商品图片" key="3">
                <Form.Item>
                <Upload
                  action="http://127.0.0.1:8888/api/private/v1/upload"
                  listType="picture-card"
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                >
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>Upload</div>
                  </div>
                </Upload>
                </Form.Item>
              </TabPane>
              <TabPane tab="商品描述" key="4">
                <QuillEditor getContent={this.getContent}/>
                <Button style={{marginTop:"10px"}} type="primary" onClick={this.addGood}>添加商品</Button>
              </TabPane>
            </Tabs>
          </Form>
        </Card>
        <Modal
          visible={this.state.previewVisible}
          title={this.state.previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt={this.state.previewTitle} style={{ width: '100%' }} src={this.state.previewImage} />
        </Modal>
      </div>
    )
  }
}
